'use strict';

module.exports = () => {
  return async (ctx, next) => {
    const { app, socket, helper, model } = ctx;
    const { id: socketId } = socket;
    const nsp = app.io.of('/');
    const user = helper.authentication(socket.handshake.query.token);
    if (user) {
      const userId = user.userInfo._id;
      nsp.once('connection', async () => {
        if (nsp.sockets[socketId]) {
          await model.Sockets.insertMany([{
            userId,
            socketId,
          }]);
        }
      });
    }
    await next();
    if (user) {
      const userId = user.userInfo._id;
      await model.Sockets.remove({
        userId,
      });
    }
  };
};
